const WebSocket = require('/home/jeff/nodejs/node_modules/ws');
const fs = require('fs');
const https = require('https');

// 加载 SSL 证书和私钥
const server = https.createServer({
    cert: fs.readFileSync('/usr/local/nginx/ssl/nginx-selfsigned.crt'),
    key: fs.readFileSync('/usr/local/nginx/ssl/nginx-selfsigned.key')
});

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ server });

//有用户连接时触发
wss.on('connection', (ws) => {
    console.log('A new client connected!');
//受到消息时触发
    ws.on('message', (message) => {
        console.log('Received:', message);

        // 假设 message 是 JSON 格式的字符串
        const data = JSON.parse(message);

        // 广播消息给所有客户端
        wss.clients.forEach((client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify(data)); // 确保发送的是 JSON 格式的文本
            }
        });
    });

    ws.on('close', () => {
        console.log('A client disconnected.');
    });
});


// 连接数限制
wss.shouldHandle = () => {
    if (wss.clients.size >= 2) {
        console.log('拒绝新连接，已达最大连接数');
        return false;
    }
    return true;
};

// 启动 HTTPS 服务器
server.listen(8888, () => {
    console.log('WebSocket server is running on wss://localhost:8888');
});